package com.itlong.cloud.controller.settings;


import com.google.zxing.BarcodeFormat;
import com.itlong.cloud.POJO.DTO.property.PropertyCloudServiceCastMessagePageDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyCloudServiceCostSaveOrderDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyInvoiceInfoDTO;
import com.itlong.cloud.POJO.PO.PropertyCloudServiceCostOrderInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.paymenthub.IAccountBalanceServiceClient;
import com.itlong.cloud.paymenthub.IPropertyCloudServiceCostServiceClient;
import com.itlong.cloud.paymenthub.IWeChatPayServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.picture.QrcodeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.rmi.runtime.Log;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *      物业—云服务费。
 * <desc/>
 *
 * @createDate 2019-08-12
 */
@RestController
@RequestMapping("settings/cloudServiceCost")
@RefreshScope
public class PropertyCloudServiceCostController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(PropertyCloudServiceCostController.class);

    @Autowired
    IPropertyCloudServiceCostServiceClient iPropertyCloudServiceCostServiceClient;

    @Autowired
    IWeChatPayServiceClient wechatPayServiceClient;

    @Autowired
    IAccountBalanceServiceClient iAccountBalanceServiceClient;

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;
    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;
    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;
    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;
    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    /**
     * <desc>
     *      获取云服务费的订单列表。
     * <desc/>
     *
     * @param  projectId 项目ID
     * @param  currentPage 当前页
     * @param  pageSize 页面大小
     * @param  feeStatus 查询条件 1待缴费 2全部
     * @param  orderColumn 排序条件
     * @param  orderRule 排序规则 ASC DESC
     * @return
     * @author Juguang.S
     * @createDate 2019-11-22
     */
    @ResponseBody
    @AuthAccessRequired
    @RequestMapping(path = "/getOrderInfo" , method = RequestMethod.POST)
    public Object getOrderInfo(String projectId,String currentPage,String pageSize,String feeStatus,String orderId,String orderColumn,String orderRule) {
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            currentPage = request.getAttribute("currentPage") == null ? null : request.getAttribute("currentPage").toString();
            pageSize = request.getAttribute("pageSize") == null ? null : request.getAttribute("pageSize").toString();
            feeStatus = request.getAttribute("feeStatus") == null ? null : request.getAttribute("feeStatus").toString();
            orderId = request.getAttribute("orderId") == null ? null : request.getAttribute("orderId").toString();
            orderColumn = request.getAttribute("orderColumn") == null ? null : request.getAttribute("orderColumn").toString();
            orderRule = request.getAttribute("orderRule") == null ? null : request.getAttribute("orderRule").toString();
            if(StringUtils.isEmpty(projectId) || StringUtils.isEmpty(feeStatus)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iPropertyCloudServiceCostServiceClient.getOrderInfo(projectId,currentPage,pageSize,feeStatus,orderId,orderColumn,orderRule));
        }catch (Exception e){
            throw new DataAccessException("【物业_获取云服务费的订单列表】失败",e);
        }
    }

    /**
     * <desc>
     *      提交云服务费订单。
     * <desc/>
     *
     * @param  orderDTO 生成订单信息
     * @return
     * @author Juguang.S
     * @createDate 2019-08-12
     */
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.CLOUD_SERVICE_ORDER_SAVE_LOG_DESC)
    @RequestMapping(path = "/order" , method = RequestMethod.POST)
    public Object saveOrder(PropertyCloudServiceCostSaveOrderDTO orderDTO) {
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            orderDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyCloudServiceCostSaveOrderDTO.class, request);
            if(orderDTO == null || StringUtils.isEmpty(orderDTO.getPayType()) || StringUtils.isEmpty(orderDTO.getFeeType()) ||
                    StringUtils.isEmpty(orderDTO.getOrderId())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //校验第三方支付管理微信支付是否被禁用
            if(wechatPayServiceClient.getThirdPayStatus(ThirdPartPayTypeEnum.WECHAT_PAY.getType())==0){
                return new MessageVO(AppErrorCodeEnum.NOT_ALLOWED_WEICHAT_TRADE.getErrorCode());
            }
            //检测是否有未支付的线下账单
            //if(iPropertyCloudServiceCostServiceClient.getIsBankPayOrder(orderDTO.getProjectId())>0){
//                return new MessageVO(PropertyErrorCodeEnum.NOT_ALLOWED_CREATE_ORDER_ERR.getErrorCode());
            //}
            //获取订单支付金额和支付状态
            PropertyCloudServiceCostOrderInfoPO infoPO = iPropertyCloudServiceCostServiceClient.getOrderAmount(orderDTO.getOrderId());
            if(infoPO == null ){
                return new MessageVO(PropertyErrorCodeEnum.ORDER_NOT_EXIST_ERR.getErrorCode());
            }
            if(infoPO.getFeeStatus()==2){
                return new MessageVO(PropertyErrorCodeEnum.BILL_PAY_SUCCESS.getErrorCode());
            }
            String billsId = orderDTO.getOrderId();
            if(orderDTO.getPayType().equals("4")){
                //微信支付，统一下单
                Map<Object,Object> resultMap = wechatPayServiceClient.saveOrder(infoPO.getPaidAmount().toString(),orderDTO.getLoginUserId(),billsId,orderDTO.getFeeType(),"", PaySourceEnum.NATIVE_SOURCE.getType(),null,null,request.getRemoteAddr(),null,null);
                if(resultMap.containsKey("codeUrl")){
                    // 生成二维码
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    BufferedImage bim = QrcodeUtils.getQR_CODEBufferedImage(resultMap.get("codeUrl").toString(), BarcodeFormat.QR_CODE, 300, 300, QrcodeUtils.getDecodeHintType());
                    ImageIO.write(bim, "jpg", os);
                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(os.toByteArray());
                    String QRCode = this.uploadFile(byteArrayInputStream);
                    if (QRCode == null) {
                        QRCode = "";
                    }
                    Map<String,String> returnMap = new HashMap<>();
                    returnMap.put("orderId",billsId);
                    returnMap.put("tradeId",resultMap.get("tradeId").toString());
                    returnMap.put("payQrcode",QRCode);
                    return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),returnMap);
                }
                else{
                    return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
                }
            }else{
                //线下银行转账
                iPropertyCloudServiceCostServiceClient.saveOrder(orderDTO);
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }

        }catch (Exception e){
            throw new DataAccessException("【物业_提交云服务费订单】失败",e);
        }
    }

    /**
     * <desc>
     *      获取物业云服务费续费记录分页信息。
     * <desc/>
     *
     * @param  pageDTO 请求参数
     * @return
     * @author Juguang.S
     * @createDate 2019-08-12
     */
    @ResponseBody
    @AuthAccessRequired
    @RequestMapping(path = "/getPaymentRecordByPage" , method = RequestMethod.POST)
    public Object getPaymentRecordByPage(PropertyCloudServiceCastMessagePageDTO pageDTO) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyCloudServiceCastMessagePageDTO.class, request);
            if(null == pageDTO || StringUtils.isEmpty(pageDTO.getProjectId())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iPropertyCloudServiceCostServiceClient.getPaymentRecordByPage(pageDTO));
        }catch (Exception e) {
            throw new DataAccessException("【物业_获取物业云服务费续费记录分页信息】失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      检测订单状态是否为完成
     * <desc/>
     *
     * @param
     * @return  标准化响应结果
     * @author Juguang.S
     * @createDate 2019/05/29
     */
    @ResponseBody
    @RequestMapping("/checkTradeSuccess")
    public Object checkTradeSuccess(String orderId,String tradeId) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            orderId = request.getAttribute("orderId") == null ? null : request.getAttribute("orderId").toString();
            tradeId = request.getAttribute("tradeId") == null ? null : request.getAttribute("tradeId").toString();
            //LOG.info("【小程序检测订单状态是否为完成】"+"orderId:"+orderId+"----tradeId:"+tradeId);
            if (StringUtils.isBlank(orderId)||StringUtils.isBlank(tradeId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Map<String,Object> map = new HashMap<>();
            if(iAccountBalanceServiceClient.checkTradeSuccess(orderId,"",tradeId)){
                //2代表订单支付成功  1代表支付未成功
                map.put("paymentStatus","2");
            }else {
                map.put("paymentStatus","1");
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),map);
        } catch (Exception e) {
            throw new DataAccessException("【物业后台】扫码支付检测订单状态是否为完成失败", e);
        }
    }

    /**
     * <desc>
     *      保存物业发票信息。
     * <desc/>
     *
     * @param  dto 物业发票信息
     * @return
     * @author Juguang.S
     * @createDate 2019-11-22
     */
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.PROPERTY_BILLING_SAVE_LOG_DESC)
    @RequestMapping(path = "/addInvoiceInfo" , method = RequestMethod.POST)
    public Object addInvoiceInfo(PropertyInvoiceInfoDTO dto) {
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto = HttpProtocolUtil.parseRequestParamToDTO(PropertyInvoiceInfoDTO.class, request);
            if(null==dto || StringUtils.isEmpty(dto.getProjectId()) || StringUtils.isEmpty(dto.getBatchNumber()) || StringUtils.isEmpty(dto.getTaxpayerName())
                    || StringUtils.isEmpty(dto.getContact()) || StringUtils.isEmpty(dto.getContactAddress()) || StringUtils.isEmpty(dto.getContactNumber())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            iPropertyCloudServiceCostServiceClient.addInvoiceInfo(dto);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【物业_获取云服务费的续费项目】失败",e);
        }
    }

    /**
     * <desc>
     *      Ftp上传文件，返回Url.
     * </desc>
     *
     * @param inputStream 文件流
     * @return 文件上传成功后会返回Url,否则返回空
     * @author Juguang.S
     * @createDate 2019/05/28
     */
    private String uploadFile(InputStream inputStream) throws IOException {
        String fileUrl = "";
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                inputStream,
                "jpg",
                FILE_ACCESS_URL,
                FileCatalogEnum.DEVICEQRCODE_FILE.getType()
        );
        Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
        Boolean returnCode = (Boolean)resultMap.get("returnCode");
        if (returnCode == false){
            return fileUrl;
        }
        fileUrl = resultMap.get("accessPath").toString();
        return fileUrl;
    }

}
